package util

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

func HttpPost(url string, data []byte, token string) ([]byte, error) {
	fmt.Printf("evcs post url: %s.\n", url)
	fmt.Printf("evcs post data: %s.\n", string(data))
	response, err := HttpPostUrl(url, data, token)
	//fmt.Println("response:", string(response))
	return response, err
}

func HttpPostUrl(url string, data []byte, token string) ([]byte, error) {
	//发送请求
	req, err := http.NewRequest("POST", url, strings.NewReader(string(data)))
	if err != nil {
		return nil, err
	}
	contentType := "application/json;charset=utf-8"
	req.Header.Set("Content-Type", contentType)
	if token != "" {
		req.Header.Set("Authorization", "Bearer "+token)
	}
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	//响应
	response, err := ioutil.ReadAll(resp.Body)
	return response, err
}
